package com.power.sifa.correction.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.aventrix.jnanoid.jnanoid.NanoIdUtils;
import com.ding.service.Di_todoRemoteService;
import com.plf.common.domain.PageDataResponse;
import com.plf.common.domain.ResponseDTO;
import com.plf.common.utils.ExcelUtil;
import com.plf.common.utils.StringUtil;
import com.power.sifa.correction.api.ICre_workFeign;
import com.power.sifa.correction.model.Cre_work;
import com.power.sifa.correction.model.Cre_work_record;
import com.power.sifa.correction.model.enumeration.St_work;
import com.power.sifa.correction.model.enumeration.Tp_crc_work;
import com.power.sifa.correction.model.pageInfo.Cre_workPageInfo;
import com.power.sifa.correction.service.Cre_workService;
import com.power.sifa.correction.service.Cre_work_recordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * 预警处置任务控制器
 */

@Slf4j
//@PowerLog
@RestController
@Api(value = "Cre_workController", tags = {"预警处置任务"})
public class Cre_workController implements ICre_workFeign {

    @Resource
    private Cre_workService cre_workService;
    @Resource
    private Di_todoRemoteService di_todoRemoteService;
    @Resource
    private Cre_work_recordService cre_work_recordService;

    @Override
    @ApiOperation("查询预警处置任务分页列表")
    @SaCheckPermission("cre_work_list")
    public ResponseDTO list(Cre_workPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo参数不能为空");
        Page<Cre_work> page = this.cre_workService.findAll(pageInfo);
        List list = new ArrayList();
        if (!page.isEmpty()) {
            for (Cre_work cre_work : page) {
                cre_work.geneText();
                list.add(cre_work);
            }
        }
        PageDataResponse p = new PageDataResponse(list, page.getTotalElements(), page.getSize(), pageInfo.getPageNumber() <= 1 ? 1 : pageInfo.getPageNumber());
        return ResponseDTO.succData(p);
    }

    @Override
    @ApiOperation("查看预警处置任务")
    @SaCheckPermission("cre_work_view")
    public ResponseDTO view(String id) {
        Assert.notNull(id, "id不能为空");
        Cre_work cre_work = cre_workService.getById(id);
        if (cre_work != null) {
            cre_work.geneText();
        }
        return ResponseDTO.succData(cre_work);
    }

    @Override
    @ApiOperation("删除预警处置任务")
    @SaCheckPermission("cre_work_del")
    public ResponseDTO delete(String id) {
        Assert.notNull(id, "id不能为空");
        cre_workService.removeById(id);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation("保存或修改预警处置任务")
    @SaCheckPermission("cre_work_save")
    public ResponseDTO save(Cre_work cre_work) {
        Assert.notNull(cre_work, "cre_work不能为空");
        cre_workService.saveOrUpdate(cre_work);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value = "批量删除预警处置任务")
    @SaCheckPermission("cre_work_del")
    public ResponseDTO batchDel(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "ids不能为空");
        List<Integer> list = Arrays.asList(ids.split(",")).stream().map(s -> Integer.parseInt(s.trim())).collect(Collectors.toList());
        cre_workService.removeByIds(list);
        return ResponseDTO.succ();
    }

    @Override
    @ApiOperation(value = "导出excel")
    @SaCheckPermission("cre_work_list")
    public void output(HttpServletResponse response, Cre_workPageInfo pageInfo) {
        Assert.notNull(pageInfo, "pageInfo不能为空");
        String title = "预警处置任务";
        String[] heads = {"序号", "预警id", "处置类型", "单位id", "单位名称", "处置人id", "处置人名称", "处置意见", "状态", "任务开始时间", "任务办结时间", "督办id", "再办id"};
        String[] fields = {"id", "warnid", "worktype", "deptid", "deptname", "userid", "username", "remark", "status", "createtime", "exectime", "supid", "repeatid"};
        Page<Cre_work> page = this.cre_workService.findAll(pageInfo);
        ExcelUtil.exportXls(title, heads, fields, page.getContent(), response);
    }

    @Override
    @ApiOperation(value = "导出excel模板")
    public void exportExcelTemplate(HttpServletResponse response) {
        String title = "预警处置任务";
        //id自增或list从表可自行删除，需与导入项一致
        String[] heads = {"序号", "预警id", "处置类型", "单位id", "单位名称", "处置人id", "处置人名称", "处置意见", "状态", "任务开始时间", "任务办结时间", "督办id", "再办id"};
        ExcelUtil.exportXls(title, heads, null, null, response);
    }

    @Override
    @ApiOperation(value = "导入excel")
    public ResponseDTO importExcel(MultipartFile file) throws IOException {
        Assert.notNull(file, "file不能为空");
        //id自增或list从表可自行删除，需与下载的模板中导入项一致
        String[] fields = {"id", "warnid", "worktype", "deptid", "deptname", "userid", "username", "remark", "status", "createtime", "exectime", "supid", "repeatid"};
        List<Cre_work> list = (List<Cre_work>) ExcelUtil.Import(fields, file, Cre_work.class);
        if (!CollectionUtils.isEmpty(list)) {
            this.cre_workService.saveAll(list);
        }
        return ResponseDTO.succ();
    }

    @Override
    public ResponseDTO queryList(Cre_workPageInfo pageInfo) {
        try {
            return ResponseDTO.succData(this.cre_workService.queryList(pageInfo));
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/cre_work/queryList 查询预警处置任务关联查询预警信息数据失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "查询预警处置任务关联查询预警信息数据失败");
        }

    }

    @Override
    public ResponseDTO updateWorktype(String workid, String warnid, Integer worktype) {
        try {
            this.cre_workService.updateWorktype(workid, warnid, worktype);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/cre_work/updateStatus 更新预警处置任务状态失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "更新预警处置任务状态失败");
        }
    }

    @Override
    public ResponseDTO complete(String id) {
        try {
            Cre_work work = this.cre_workService.getById(id);
            if (Tp_crc_work.UNDO == work.getWorktype()) {
                return ResponseDTO.wrap(500, "请修改核实情况");
            }
            // 1. 完成赣政通待办任务
            if(!StringUtil.isEmpty(work.getTodoid())) {
//                this.di_todoRemoteService.afterValidateFinishTodo(work.getTodoid());
            }
            // 2. 更新预警处置状态和办结时间
            this.cre_workService.updateStatus(id, St_work.DONE, new Date());
            // 3. 保存一条系统完成记录
            Cre_work_record recordObj = new Cre_work_record();
            recordObj.setId(work.getId() + NanoIdUtils.randomNanoId());
            recordObj.setExectime(new Date());
            recordObj.setWorkid(work.getId());
            recordObj.setRecord("预警处置完成。（系统已办结任务）");
            this.cre_work_recordService.saveOrUpdate(recordObj);
            return ResponseDTO.succ();
        } catch (Exception e) {
            e.printStackTrace();
            log.error("/cre_work/complete 预警任务处置完成失败 ->  msg[{}]", e.getMessage());
            return ResponseDTO.wrap(500, "预警任务处置完成失败");
        }

    }

    @Override
    public ResponseDTO getDisposalStatus(List<String> f_deptid) {
//        Assert.notNull(f_deptid, "adId不能为空");
        try {
            return ResponseDTO.succData(this.cre_workService.getDisposalStatus(f_deptid));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseDTO.wrap(500, "获取预警处置任务状态失败");
    }

    @Override
    public ResponseDTO findProcess(String warnId) {
        Assert.notNull(warnId, "warnId不能为空");
        try {
            return ResponseDTO.succData(this.cre_workService.findProcess(warnId));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseDTO.wrap(500, "获取处置流程失败");
    }

}
